# LOAD NECESSARY PACKAGES ------------------------------------------------------

library(pacman)

# tidyverse
p_load(dplyr, tidyr, stringr, forcats, purrr, ggplot2, geomtextpath)

#devtools::install_github("bcallaway11/did")

# analysis
p_load(naniar, fixest, did, modelsummary, broom)

# misc
p_load(here)

#sem
std <- function(x) sd(x, na.rm = T)/sqrt(length(x))

# LOAD DATA --------------------------------------------------------------------

gdldata <- tibble()

for (i in list.files(here("Data", "GDL"))) {
  
data <- tibble(read.csv(here("Data", "GDL", i))) %>% 
  mutate(variable = str_extract(i, pattern = ".+?(?=.csv)"))

gdldata <- rbind(gdldata, data)
  
}

# VISUALISE DATA ---------------------------------------------------------------

gdldata %>% 
  select(-c(ISO_Code, GDLCODE, Level)) %>% 
  pivot_longer(-c(Country, Region, variable)) %>% 
  filter(Region %in% c("Total", "Rural")) %>% 
  mutate(Region = factor(Region, levels = c("Total", "Rural", "Urban")),
         Year = factor(as.numeric(str_remove(name, "X"))),
         variable = case_when(
           variable == "elec" ~ "Electrification rate (%)",
           variable == "iwi" ~ "International wealth index",
           variable == "educ" ~ "Avg. years of educ. (adults)",
           variable == "fert" ~ "Total fertility rate",
           variable == "urb" ~ "Urban population share (%)",
           variable == "emp_agg_men" ~ "Share men farm employed (%)",
           variable == "emp_lownf_men" ~ "Share men non-farm employed (%)",
           variable == "emp_uppnf_men" ~ "Share men non-farm employed (%)",
           variable == "emp_agg_wmn" ~ "Share women farm employed (%)",
           variable == "emp_lownf_wmn" ~ "Share women non-farm employed (%)",
           variable == "emp_uppnf_wmn" ~ "Share women non-farm employed (%)",
           variable == "patr" ~ "Patrilocality index",
           variable == "pop" ~ "Total population (Millions)"
         )) %>% 
  group_by(Year, Region, Country, variable) %>% 
  summarise(value = sum(value)) %>% 
  ggplot(aes(Year, value, linetype = Region, colour = Country, 
             group = interaction(Country, Region, variable), 
             label = paste(Country, Region))) +
  geom_textline(show.legend = F, size = 3) +
  scale_x_discrete(breaks = seq(2006,2015, by = 3)) +
  facet_wrap(~variable, scales = "free", strip.position = "left") +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 30, hjust = 1)) +
  labs(x = NULL, y = NULL)

ggsave(filename = here("Manuscript", "Figures", "background.png"), 
       width = 10, height = 8)
